# 启动生产环境脚本
Write-Host "启动小说阅读应用生产环境..." -ForegroundColor Green

# 确保目录存在
if (-not (Test-Path data)) {
    New-Item -ItemType Directory -Path data
    Write-Host "已创建数据目录: data" -ForegroundColor Yellow
}

if (-not (Test-Path novels)) {
    New-Item -ItemType Directory -Path novels
    Write-Host "已创建小说目录: novels" -ForegroundColor Yellow
    Write-Host "请将TXT小说文件放入novels目录中" -ForegroundColor Yellow
}

# 检查data/novels.db是否存在，如果不存在，提示用户
if (-not (Test-Path data/novels.db)) {
    Write-Host "数据库文件不存在，首次运行将自动创建" -ForegroundColor Yellow
}

# 启动后端服务
Write-Host "正在启动后端服务..." -ForegroundColor Cyan
$serverProcess = Start-Process -FilePath "node" -ArgumentList "server/src/app.js" -PassThru -NoNewWindow

# 使用serve启动前端
Write-Host "正在启动前端服务..." -ForegroundColor Cyan
if (-not (Test-Path 'C:\Users\*\AppData\Roaming\npm\serve.cmd')) {
    Write-Host "未找到serve命令，正在全局安装..." -ForegroundColor Yellow
    npm install -g serve
}

$clientProcess = Start-Process -FilePath "serve" -ArgumentList "-s client/build -l 3000" -PassThru -NoNewWindow

Write-Host "应用已成功启动!" -ForegroundColor Green
Write-Host "前端地址: http://localhost:3000" -ForegroundColor Green
Write-Host "后端API地址: http://localhost:3001/api" -ForegroundColor Green
Write-Host "按任意键停止服务..." -ForegroundColor Red

# 等待用户输入以停止服务
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

# 停止服务
Write-Host "正在停止服务..." -ForegroundColor Yellow
Stop-Process -Id $serverProcess.Id -Force
Stop-Process -Id $clientProcess.Id -Force

Write-Host "服务已停止" -ForegroundColor Green 